<template>
	<view class="flex justify-center">
		<view class="bg-white p-2" style="border: 2rpx solid #eee;width: 90%;">
			<view class="flex chat">
				<!-- 右 -->
				<view class="bg-light flex-1 flex flex-column a" id="scrollview" style="height: 1200rpx;">
					<!-- 聊天消息区 -->
					<view class="bg-light scroll-view mb-2 a" style="border: 2rpx solid #eee;overflow-y: scroll;">
						<scroll-view :scroll-top="scrollTop" :scroll-y="true" :style="{height:scrollViewHeight+'rpx'}" id="msglistview" class="chat-body">
							<!-- 聊天记录 -->
							<view v-for="(item,index) in msgList" :key="index">
								<!-- 自己发的消息 -->
								<view class="item self" v-if="item.userContent != ''">
									<!-- 文字内容 -->
									<view class="flex flex-column align-center">
										<text class="font-small">{{item.time}}</text>
										<view class="content right">
											{{item.userContent}}
										</view>
									</view>
									<!-- 头像 -->
									<view class="flex flex-column align-center">
										<image mode="widthFix" style="width: 70rpx;" class="avatar" src="https://digital.essc.top/dist/zjl_icon/user.png">
										</image>
									</view>
								</view>
								<!-- 机器人发的消息 -->
								<view class="item Ai" v-if="item.botContent != ''">
									<!-- 头像 -->
									<view class="flex flex-column align-center">
										<image mode="widthFix" style="width: 70rpx;" class="avatar" src="https://digital.essc.top/dist/zjl_icon/user.png">
										</image>
									</view>
									<!-- 文字内容 -->
									<view class="flex flex-column align-center">
										<text class="font-small">{{item.time}}</text>
										<view style="position: relative;" class="content left">
											{{item.botContent}}
										</view>
									</view>
								</view>
							</view>
						</scroll-view>
					</view>
					<!-- 发送消息区 -->
					<view class="p-4">
						<view class="flex justify-between w-100">
							<view class="send-msg a" style="width: 70%; height: 100rpx; overflow-y: scroll;">
								<textarea style="width: 100%;"  v-model="chatMsg"  maxlength="300" confirm-type="send" @confirm.stop="handleSend"
									placeholder="快来聊天吧~" :show-confirm-bar="false" :adjust-position="false" @linechange.stop="sendHeight"
									@focus.stop="focus" @blur.stop="blur" auto-height></textarea>
							</view>
							<view class="flex-1">
								<button @click.stop="handleSend" style="height: 100%;background-color: burlywood;"
									class="flex justify-center align-center" type="default">发送</button>
							</view>
						</view>
					</view>
				</view>
			</view>
		</view>
	</view>
</template>

<script>
	const app = getApp()
	import times from '@/mixins/time.js'
	export default {
		name: "Tradingchat2",
		data() {
			return {
				usePhone:"",
				height:"",
				socketTask: null,//websocket
				is_open_socket: false,// 确保websocket是打开状态
				hearBeatInterval: null,//心跳
				//键盘高度
				keyboardHeight: 0,
				//底部消息发送高度
				bottomHeight: 0,
				//滚动距离
				scrollTop: 1200,
				scrollViewHeight:1200,
				userId: '',
				//发送的消息
				chatMsg: "",
				// userImage: app.globalData.memberInfo.Image,
				// serveImage:app.globalData.memberInfo.Image,
				msgList: [
					{
						botContent: "你好啊",
						userContent: "",
						time:"",
					},
				]
			}
		},
		props:{
			Enterprise_Info_SerialNumber:{
				type:String,
				default:''
			},
			shows:{
				type:Boolean,
				default:false
			}
		},
		// updated() {
		// 	//页面更新时调用聊天消息定位到最底部
		// 	this.scrollToBottom();
		// },
		computed: {

		},
		onLoad() {
			this.usePhone = uni.getStorageSync('use')
			this.connectSocketInit()
			console.log(this.usePhone)
			// uni.onKeyboardHeightChange(res => {
			// 	this.keyboardHeight = this.rpxTopx(res.height)
			// 	if (this.keyboardHeight < 0) this.keyboardHeight = 0;
			// })
		},
		onShow() {

		},
		beforeDestroy() {
			this.closeSocket()
		},
		mounted(){
			// this.closeSocket()
			this.usePhone = uni.getStorageSync('use')
			this.GetList()
			this.connectSocketInit()
		},
		unmounted(){
			this.closeSocket()
		},
		methods: {
			focus() {
				console.log(this.Enterprise_Info_SerialNumber)
				this.scrollToBottom()
			},
			blur() {
				this.scrollToBottom()
			},
			// px转换成rpx
			rpxTopx(px) {
				let deviceWidth = uni.getSystemInfoSync().windowWidth
				let rpx = (750 / deviceWidth) * Number(px)
				return Math.floor(rpx)
			},
			// 监视聊天发送栏高度
			sendHeight() {
				setTimeout(() => {
					let query = uni.createSelectorQuery();
					query.select('.send-msg').boundingClientRect()
					query.exec(res => {
						this.bottomHeight = this.rpxTopx(res[0].height)
					})
				}, 10)
			},
			// 滚动至聊天底部
			scrollToBottom() {
				this.$nextTick(() => {
					uni.createSelectorQuery().in(this).select('#msglistview').boundingClientRect((res) => {
						let top = this.scrollViewHeight + res.height;
						console.log(top)
						if (top > 0) {
							this.scrollTop = 1800;
						}
						console.log(res)
					}).exec()
				})
			},
			// 发送消息
			handleSend() {
				//如果消息不为空
				this.scrollToBottom()
				if (!this.chatMsg || !/^\s+$/.test(this.chatMsg)) {
					let time = times.nowtime();
					let obj = {
						botContent: "",
						userContent: this.chatMsg,
						time:times.nowtime()
					}
					this.msgList.push(obj);
					if(this.is_open_socket&&this.chatMsg!=""){
						console.log(1);
						this.socketTask.send({
							data: JSON.stringify({
								time,
								message:this.chatMsg,
								userId:this.Enterprise_Info_SerialNumber,
							}),
							async success() {
								console.log("消息发送成功");
							},
						});
						this.setMessage(this.usePhone,this.chatMsg,time)
					}
					this.chatMsg = ''
				} else {
					uni.showToast({
						title: '不能发空消息哦',
						icon: 'error'
					})
				}

			},
			GetList(){
				uni.request({ //
					url: app.globalData.Domain_Name + '/GroupServesHistory',
					header: {
						'Content-Type': 'application/x-www-form-urlencoded'
					},
					method: "POST",
					data: {
						Group_ID:this.usePhone,
						User_Type:'custom',
						Enterprise_Info_SerialNumber:this.Enterprise_Info_SerialNumber,
					},
					success: (res) => {
						this.scrollTop = 1800
						console.log(res.data);
						this.msgList = res.data.Data
					}
				})
			},
			connectSocketInit() {
				// 创建一个this.socketTask对象【发送、接收、关闭socket都由这个对象操作】
				this.socketTask = uni.connectSocket({
					url: "wss"+(app.globalData.Domain_Name).slice(5)+"/websocket?userId=Group"+this.usePhone,
					success(data) {
						console.log("websocket连接成功");
					},
				});
				// // 消息的发送和接收必须在正常连接打开中,才能发送或接收【否则会失败】
				this.socketTask.onOpen((res) => {
					console.log("WebSocket连接正常打开中...！");
					this.is_open_socket = true;
					// 注：只有连接正常打开中 ，才能正常成功发送消息
					this.hearBeatInterval = setInterval(()=>{
						this.socketTask.send({
							data: 'ping',
						});
					},5000)
					// 注：只有连接正常打开中 ，才能正常收到消息
					this.socketTask.onMessage((res) => {
						console.log(JSON.parse(res.data))
						let time = JSON.parse(res.data).data.time
						let message = JSON.parse(res.data).data.message
						this.msgList.push({
							botContent:message,
							userContent: "",
							time,
						});
					});
				})
				// // 这里仅是事件监听【如果socket关闭了会执行】
				this.socketTask.onClose(() => {
					this.is_open_socket = false;
					clearInterval(this.hearBeatInterval)
					console.log("已经被关闭了")
				})
			},
			// 关闭websocket【离开这个页面的时候执行关闭】
			closeSocket() {
				if(this.is_open_socket){
					this.socketTask.close()
					clearInterval(this.hearBeatInterval)
				}
			},
			clickRequest() {
				if (this.is_open_socket) {
					// websocket的服务器的原理是:发送一次消息,同时返回一组数据【否则服务器会进去死循环崩溃】
					this.socketTask.send({
						data: "请求一次发送一次message",
						async success() {
							console.log("消息发送成功");
						},
					});
				}
			},
			setMessage(Group_User_Number,Group_Message,Group_Message_Time){//保存消息到历史记录
				uni.request({
					url: app.globalData.Domain_Name + '/GoodsFileAdd',
					header: {
						'Content-Type': 'application/x-www-form-urlencoded'
					},
					method: "POST",
					data: {
						Data:JSON.stringify({
							group_serves_news:[{
								Group_Serves_SerialNumber:'',
								Group_User_Number,
								Group_Serves_ID:this.Enterprise_Info_SerialNumber,
								Group_Message,
								Group_Message_Time,
								Group_Message_Type:'',
								Enterprise_Info_SerialNumber:this.Enterprise_Info_SerialNumber,
								Row_Status:'0'
							}]
						}),
					},
					success: (res) => {
						console.log('已保存到历史记录');
					}
				})
			},

		}
	}
</script>

<style lang="scss">
	$chatContentbgc: #C2DCFF;
	$sendBtnbgc: #4F7DF5;

	.chat {
		.topTabbar {
			width: 100%;
			height: 90rpx;
			line-height: 90rpx;
			display: flex;
			margin-top: 80rpx;
			justify-content: space-between;

			.icon {
				margin-left: 20rpx;
			}

			.text {
				margin: auto;
				font-size: 16px;
				font-weight: 700;
			}

			.button {
				width: 10%;
				margin: auto 20rpx auto 0rpx;
			}
		}

		.scroll-view {
			::-webkit-scrollbar {
				display: none;
				width: 0 !important;
				height: 0 !important;
				-webkit-appearance: none;
				background: transparent;
				color: transparent;
			}

			// background-color: orange;
			background-color: #F6F6F6;

			.chat-body {
				display: flex;
				flex-direction: column;
				padding-top: 23rpx;
				// background-color:skyblue;

				.self {
					justify-content: flex-end;
				}

				.item {
					display: flex;
					padding: 23rpx 30rpx;
					// background-color: greenyellow;

					.right {
						background-color: $chatContentbgc;
					}

					.left {
						background-color: #FFFFFF;
					}

					// 聊天消息的三角形
					.right::after {
						position: absolute;
						display: inline-block;
						content: '';
						width: 0;
						height: 0;
						left: 100%;
						top: 10px;
						border: 12rpx solid transparent;
						border-left: 12rpx solid $chatContentbgc;
					}

					.left::after {
						position: absolute;
						display: inline-block;
						content: '';
						width: 0;
						height: 0;
						top: 10px;
						right: 100%;
						border: 12rpx solid transparent;
						border-right: 12rpx solid #FFFFFF;
					}

					.content {
						position: relative;
						max-width: 486rpx;
						border-radius: 8rpx;
						word-wrap: break-word;
						padding: 24rpx 24rpx;
						margin: 0 24rpx;
						border-radius: 5px;
						font-size: 32rpx;
						font-family: PingFang SC;
						font-weight: 500;
						color: #333333;
						line-height: 42rpx;
					}

					.avatar {
						display: flex;
						justify-content: center;
						width: 78rpx;
						height: 78rpx;
						border-radius: 50rpx;
						overflow: hidden;

						image {
							align-self: center;
						}

					}
				}
			}
		}

		/* 底部聊天发送栏 */
		.chat-bottom {
			width: 100%;
			height: 100rpx;
			background: #F4F5F7;
			transition: all 0.1s ease;

			.send-msg {
				display: flex;
				align-items: flex-end;
				padding: 16rpx 30rpx;
				width: 100%;
				min-height: 177rpx;
				position: fixed;
				bottom: 0;
				background: #fff;
				transition: all 0.1s ease;
			}
			.uni-textarea {
				padding-bottom: 70rpx;

				textarea {
					width: 537rpx;
					min-height: 75rpx;
					max-height: 500rpx;
					background: #f1f1f1;
					border-radius: 40rpx;
					font-size: 32rpx;
					font-family: PingFang SC;
					color: #333333;
					line-height: 74rpx;
					padding: 5rpx 8rpx;
					text-indent: 30rpx;
				}
			}

			.send-btn {
				display: flex;
				align-items: center;
				justify-content: center;
				margin-bottom: 76rpx;
				margin-left: 25rpx;
				width: 120rpx;
				height: 75rpx;
				background: #ed5a65;
				border-radius: 50rpx;
				font-size: 28rpx;
				font-family: PingFang SC;
				font-weight: 500;
				color: #FFFFFF;
				line-height: 28rpx;
			}
		}
	}
	// .a::-webkit-scrollbar{
	//     display: none;
	// }
</style>